package com.chenyue.cm.user.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.base.bean.PageVo;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.Constants;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.common.utils.StringUtils;
import com.chenyue.cm.user.domain.JdGoodsSku;
import com.chenyue.cm.user.domain.JdGoodsSkuExample;
import com.chenyue.cm.user.service.JdGoodsSkuService;
import com.chenyue.cm.user.service.JdGoodsSpuService;
import com.chenyue.cm.user.domain.JdGoodsSpu;
import com.chenyue.cm.user.domain.JdGoodsSpuExample;
import com.chenyue.cm.utils.FreeMarkerUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
* @author chenyue-cm
* @date 2024-02-29
*/
@RestController
@RequestMapping("/jdGoodsSpu")
public class JdGoodsSpuController {

    @Autowired
    private JdGoodsSpuService mGoodsSpuService;
    @Autowired
    private JdGoodsSkuService mGoodsSkuService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/getList")
    @ResponseBody
    public Success<PageVo<JdGoodsSpu>> getList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<JdGoodsSpu> result = mGoodsSpuService.getPageBean(pageInfo, JdGoodsSpu.class);
        return Success.success(result);
    }


    /**
     * @param vo
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    @Log(value = "商品基础信息- 保存商品基础信息数据", type = "2", module = "2")
    public Success save(JdGoodsSpu vo, HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");

        if (id != null && id != "") {
            mGoodsSpuService.getBaseMapper().updateById(vo);
        } else {
            vo.setId(UUID.randomUUID().toString().replace("-", ""));
            mGoodsSpuService.save(vo);
        }

        return Success.success();
    }


    /**
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/delete/{id}")
    @ResponseBody
    @Log(value = "商品基础信息- 删除商品基础信息数据", type = "2", module = "2")
    public Success delete(@PathVariable String id, HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");

        JdGoodsSpuExample aExample = new JdGoodsSpuExample();
        aExample.createCriteria().andIdEqualTo(id);
        mGoodsSpuService.deleteByExample(aExample);

        return Success.success();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    @Log(value = "商品基础信息- 删除多个数据", type = "2", module = "2")
    public Success delete(HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");
        String ids = request.getParameter("ids");
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            mGoodsSpuService.deleteByPrimaryKey(idString);
        }
        return Success.success();
    }

    /**
     * 【API】----  修改订单信息（订单状态:上架/下架）
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/updateGoodsState")
    @ResponseBody
    @Log
    public Success updateGoodsState(HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        String state = request.getParameter("state");
        if (com.chenyue.cm.common.utils.StringUtils.isEmpty(id)) {
            return Success.error("id不能为空");
        }
        if (com.chenyue.cm.common.utils.StringUtils.isEmpty(state)) {
            return Success.error("商品状态不能为空");
        }
        // 查询商品信息
        JdGoodsSpu goodsSpu = this.mGoodsSpuService.selectByPrimaryKey(id);
        if (goodsSpu == null) {
            return Success.error("未查询到商品信息");
        }
        switch (state) {
            case "0": // 前台已经调用order验证是否存在未完成订单且提示过用户
            case "1":
                // 验证是否存在规格
                JdGoodsSkuExample goodsSkuExample = new JdGoodsSkuExample();
                goodsSkuExample.createCriteria().andGoodsIdEqualTo(goodsSpu.getId());
                List<JdGoodsSku> skuList = mGoodsSkuService.selectByExample(goodsSkuExample);
                if (skuList == null || skuList.size() < 1) {
                    return Success.error("规格信息不存在，请先设置规格");
                }
                if (skuList.size() > 1 && StringUtils.isEmpty(goodsSpu.getUpdateUser())) {
                    return Success.error("规格设置发生异常，请重新设置");
                }
        }
        //更新商品状态
        goodsSpu.setState(Integer.valueOf(state));
        this.mGoodsSpuService.updateById(goodsSpu);
        return Success.success();
    }

    /**
     * 商品概括
     *
     * @return
     */
    @RequestMapping(value = "/getGoodsSummary", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
    })
    @ApiOperation(value = "【G1008】商品概括", notes = "商品概括")
    @ApiOperationSupport(order = 8)
    public Success getGoodsSummary() {
        LambdaQueryWrapper<JdGoodsSpu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdGoodsSpu::getState, Constants.COMMON_STATUS_1);
        int goodsCount = mGoodsSpuService.count(wrapper);
        return Success.success(goodsCount);
    }

    /**
     * 按支付金额排序
     */
    @RequestMapping("/getGoodsOrderList")
    @ResponseBody
    public Success<PageVo<JdGoodsSpu>> getGoodsOrderList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Pageable pageInfo = RequestUtil.getPageable(request);

        PageVo<JdGoodsSpu> result = mGoodsSpuService.getPageBean(pageInfo, JdGoodsSpu.class);
        HashMap<String, java.lang.Object> paramMap = new HashMap<>();
        paramMap.put("page", (pageInfo.getPageIndex() - 1) * pageInfo.getPageSize());
        paramMap.put("rows", pageInfo.getPageSize());
        paramMap.put("flag", request.getParameter("flag"));
        String Content = FreeMarkerUtils.getTemplateContent("getGoodsListByPayMoney.ftl", paramMap);
        System.out.println(Content);
        List<Map<String, Object>> mList = jdbcTemplate.queryForList(Content);
        List<JdGoodsSpu> voList = com.alibaba.fastjson.JSON.parseObject(JSON.toJSONString(mList), new TypeReference<List<JdGoodsSpu>>() {
        });
        result.setContent(voList);
        return Success.success(result);
    }

}
